package com.mission.schedule.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request.Method;
import com.android.volley.toolbox.StringRequest;
import com.baidu.mobads.sdk.api.RequestParameters;
import com.baidu.mobads.sdk.api.SplashAd;
import com.baidu.mobads.sdk.api.SplashInteractionListener;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.mission.schedule.CommonDialog.UserProtocolTipDialog;
import com.mission.schedule.R;
import com.mission.schedule.ad.AdSettingHelper;
import com.mission.schedule.ad.AdSettingProperties;
import com.mission.schedule.annotation.ViewResId;
import com.mission.schedule.applcation.App;
import com.mission.schedule.clock.WriteAlarmClock;
import com.mission.schedule.constants.ShareFile;
import com.mission.schedule.constants.URLConstants;
import com.mission.schedule.db.DBSourse;
import com.mission.schedule.entity.CLAdsTable;
import com.mission.schedule.service.DownQianDaoService;
import com.mission.schedule.service.UpdataTagService;
import com.mission.schedule.utils.CharacterUtil;
import com.mission.schedule.utils.DateUtil;
import com.mission.schedule.utils.GetDeviceId;
import com.mission.schedule.utils.ImageFileCache;
import com.mission.schedule.utils.ProgressUtil;
import com.mission.schedule.utils.ScreenUtils;
import com.mission.schedule.utils.SharedPrefUtil;
import com.mission.schedule.utils.StringUtils;
import com.mission.schedule.utils.UiUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;

@SuppressLint({"SdCardPath", "HandlerLeak"})
public class WelcomeActivity extends BaseActivity implements OnClickListener {


    @ViewResId(id = R.id.bj_image)
    private ImageView bj_image;// 大背景
    @ViewResId(id = R.id.background_rl)
    private RelativeLayout background_rl;// 大背景
    @ViewResId(id = R.id.date_rl)
    private RelativeLayout date_rl;// 日期大背景
    @ViewResId(id = R.id.month_tv)
    private TextView month_tv;// 今天3月
    @ViewResId(id = R.id.day_tv)
    private TextView day_tv;// 28号
    @ViewResId(id = R.id.week_tv)
    private TextView week_tv;// 星期三
    @ViewResId(id = R.id.qiandao_ll)
    private LinearLayout qiandao_ll;// 签到背景
    @ViewResId(id = R.id.tiaoguo_tv)
    private TextView tiaoguo_tv;// 跳过
    @ViewResId(id = R.id.nextfenshu_tv)
    private TextView nextfenshu_tv;// 下次签到+1
    @ViewResId(id = R.id.jieri_ll)
    private LinearLayout jieri_ll;// 节日线性布局
    @ViewResId(id = R.id.year_tv)
    private TextView year_tv;// 如 2016-02-07
    @ViewResId(id = R.id.jieri_week_tv)
    private TextView jieri_week_tv;// 周日
    @ViewResId(id = R.id.jieri_nongli_tv)
    private TextView jieri_nongli_tv;
    @ViewResId(id = R.id.jieri_tv)
    private TextView jieri_tv;
    @ViewResId(id = R.id.qiandaoadd_tv)
    private TextView qiandaoadd_tv;
    @ViewResId(id = R.id.text)
    private TextView text;
    @ViewResId(id = R.id.text1)
    private TextView text1;
    @ViewResId(id = R.id.outbackground_ll)
    private LinearLayout outbackground_ll;
    @ViewResId(id = R.id.adsRl)
    private RelativeLayout adsParent;


    private String userId = "";// 用户id
    SharedPrefUtil sharePrefUtil;
    private String isUserFirstInstall = "";
    private static final String CACHDIR = "ImgCach";

    Context context;

    List<Map<String, String>> nongliList = new ArrayList<Map<String, String>>();

    String updateState = "1";
    App app = App.getDBcApplication();
    String downtime = "";
    String downImgTime = "";
    String today;
    String tommrow;
    String week;// 周二
    String myweek;// 星期2
    Map<String, String> mMap = null;
    String imagePath = "";
    private ImageFileCache fileCache;
    String qiandaoDate = "";
    int month;
    int day;
    int type;
    boolean qiandaoFag = true;

    //百度广告
    // 推荐使用全局变量，以便统一释放资源
    private SplashAd splashAd;
    private boolean canJumpImmediately = false;
    private boolean isStartActivity = true;
    private boolean isClickAd = false;

    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    Toast.makeText(WelcomeActivity.this, "出错了...",
                            Toast.LENGTH_SHORT).show();

                    break;
                case 1:
                    Toast.makeText(WelcomeActivity.this, "存储卡不可用，请确认已插入卡后再使用本程序",
                            Toast.LENGTH_SHORT).show();
                    WelcomeActivity.this.finish();

                    break;
                case 2:
                    progressUtil.dismiss();
                    break;
            }
        }

    };

    @Override
    protected void setListener() {
        qiandao_ll.setOnClickListener(this);
        tiaoguo_tv.setOnClickListener(this);
        bj_image.setOnClickListener(this);
    }

    String welcome_login_type = "1";

    @Override
    protected void setContentView() {
        // 隐藏标题栏
//        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 隐藏状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_welcomeactivity);
    }

    @SuppressWarnings("deprecation")
    @Override
    protected void init(Bundle savedInstanceState) {
        Log.e("TAG", "welcome1");
        context = this;
        sharePrefUtil = new SharedPrefUtil(this, ShareFile.USERFILE);
        fileCache = new ImageFileCache();
        userId = sharePrefUtil.getString(context, ShareFile.USERFILE, ShareFile.USERID, "0");
        isUserFirstInstall = sharePrefUtil.getString(context, ShareFile.USERFILE, ShareFile.ISUSERFIRSTINSTALL, "");
        welcome_login_type = sharePrefUtil.getString(context, ShareFile.USERFILE, ShareFile.WELCOMETOLOGIN, "1");
        updateState = sharePrefUtil.getString(context, ShareFile.USERFILE, ShareFile.UPDATESTATE, "0");
        qiandaoDate = sharePrefUtil.getString(context, ShareFile.USERFILE, ShareFile.QIANDAODATE, DateUtil.formatDate(new Date()));
        if (DateUtil.formatDate(new Date()).equals(qiandaoDate)) {
            qiandaoFag = false;
        } else {
            sharePrefUtil.putString(context, ShareFile.USERFILE, ShareFile.TYPEINDEX, "3");
            sharePrefUtil.putString(context, ShareFile.USERFILE, ShareFile.TYPEUID, "");
        }
        sharePrefUtil.putString(context, ShareFile.USERFILE, ShareFile.APPWIDGETADDTYPE, "0");
        Typeface typeFace = Typeface.createFromAsset(getAssets(), "fonts/pop.ttf");
        Calendar calendar = Calendar.getInstance();
        today = DateUtil.formatDate(calendar.getTime());
        month = calendar.get(Calendar.MONTH) + 1;
        day = calendar.get(Calendar.DATE);
        calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) + 1);
        tommrow = DateUtil.formatDate(calendar.getTime());
        week = CharacterUtil.getWeekOfDate(context, DateUtil.parseDate(today));
        myweek = CharacterUtil.getWeekOfDate1(context, DateUtil.parseDate(today));
//        month_tv.setTypeface(typeFace);
//        day_tv.setTypeface(typeFace);
//        week_tv.setTypeface(typeFace);
//        year_tv.setTypeface(typeFace);
//        jieri_week_tv.setTypeface(typeFace);
//        jieri_nongli_tv.setTypeface(typeFace);
//        jieri_tv.setTypeface(typeFace);
//        qiandaoadd_tv.setTypeface(typeFace);
//        nextfenshu_tv.setTypeface(typeFace);
//        tiaoguo_tv.setTypeface(typeFace);
//        text.setTypeface(typeFace);
//        text1.setTypeface(typeFace);
//        Log.e("TAG","welcome2");
    }

    /**
     * 不可点击的开屏，使用该jump方法，而不是用jumpWhenCanClick
     */
    private void jump() {
        if (canJumpImmediately) {
            if (splashAd != null) {
                Intent intent = LoaddingData(isStartActivity, type);
                /**
                 * 1. 结束当前Activity并启动主页，建议在该方法的回调中执行开屏Activity的结束操作。
                 * 2. 若仅传入Intent而不设置回调，则会在启动主页后自动结束当前开屏Activity，
                 *    例如： {@link SplashAd#finishAndJump(Intent)}
                 * 3. 建议配合主页onCreate阶段中的 {@link SplashAd#registerEnterTransition(
                 *Activity, SplashAd.SplashFocusAdListener)} 使用
                 */
                splashAd.finishAndJump(intent, new SplashAd.OnFinishListener() {
                    @Override
                    public void onFinishActivity() {
                        finish();
                    }
                });
                splashAd.destroy();
            }
        }
    }

    private void jumpWhenCanClick() {
        if (canJumpImmediately) {
            if (splashAd != null) {
                Intent intent = LoaddingData(isStartActivity, type);
                /**
                 * 1. 结束当前Activity并启动主页，建议在该方法的回调中执行开屏Activity的结束操作。
                 * 2. 若仅传入Intent而不设置回调，则会在启动主页后自动结束当前开屏Activity，
                 *    例如： {@link SplashAd#finishAndJump(Intent)}
                 * 3. 建议配合主页onCreate阶段中的 {@link SplashAd#registerEnterTransition(
                 *Activity, SplashAd.SplashFocusAdListener)} 使用
                 */
                splashAd.finishAndJump(intent, new SplashAd.OnFinishListener() {
                    @Override
                    public void onFinishActivity() {
                        finish();
                    }
                });
                if (isClickAd){
                    isClickAd = false;
                    startActivity(intent);
                    finish();
                }
                splashAd.destroy();
            }
        } else {
            canJumpImmediately = true;
        }

    }

    //测试图片
    String ceimage = "http://121.40.19.103/timetable/TbDU_showImage.htm?imageName=20161101/302268.jpg&imageType=10&imageSizeType=1";

    private void LoadData() {
        if ("0".equals(userId) || "".equals(userId)) {
            new WriteDataBase().execute();
            type = 0;
            background_rl.setVisibility(View.GONE);
            handler.postDelayed(runnable, 200);
        } else {
            if (DateUtil.formatDate(new Date()).equals(qiandaoDate)) {
                background_rl.setVisibility(View.GONE);
                type = 0;
                handler.postDelayed(runnable, 200);
            } else {
                background_rl.setVisibility(View.VISIBLE);
                type = 1;
                app.updateQianDaoImgData("20160329111518", "20160320/788373.jpg", "");
                mMap = app.QueryQianDaoImgData(today, 0);
                if (mMap != null && mMap.size() > 0) {
                    imagePath = mMap.get(CLAdsTable.adsImagePath);

                    if (!"".equals(StringUtils.getIsStringEqulesNull(imagePath))) {

                        String dicr = Environment.getExternalStorageDirectory() + "/DCIM/";
                        File outfile = new File(dicr, "TimeApp");
                        // 如果文件不存在，则创建一个新文件
                        if (!outfile.isDirectory()) {
                            try {
                                outfile.mkdir();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        Bitmap bitmap = BitmapFactory.decodeFile(outfile + "/" + imagePath.replace('/', '0'));

                        if (bitmap == null) {

                            DisplayImageOptions options = new DisplayImageOptions.Builder()
                                    .showStubImage(R.mipmap.tmbj)          // 设置图片下载期间显示的图片
                                    .showImageForEmptyUri(R.mipmap.tmbj)  // 设置图片Uri为空或是错误的时候显示的图片
                                    .showImageOnFail(R.mipmap.tmbj)       // 设置图片加载或解码过程中发生错误显示的图片
                                    .cacheInMemory(true)                        // 设置下载的图片是否缓存在内存中
                                    .cacheOnDisc(true)                          // 设置下载的图片是否缓存在SD卡中
                                    .build();

                            String imageurl = URLConstants.HOST + "/TbDU_showImage.htm?imageName="
                                    + StringUtils.getIsStringEqulesNull(imagePath) + "&imageType=10&imageSizeType=1";
                            //加载图片
                            ImageLoader.getInstance().displayImage(imageurl, bj_image, options);
                        } else {
                            bj_image.setImageBitmap(bitmap);
                        }
                    } else {
                        LoaddingData(isStartActivity, 0);
                    }
                    if (Environment.getExternalStorageState().equals(
                            Environment.MEDIA_MOUNTED)) {
                        if (getUserState().equals("1"))
                            userId = sharePrefUtil.getString(this, ShareFile.USERFILE, ShareFile.USERID, "");
                    } else {
                        handler.sendEmptyMessage(1);
                    }
                } else {
                    type = 0;
                    handler.postDelayed(runnable, 200);
                }
                IntenetData();
            }
        }
    }

    public Bitmap getBitmap(final String url) {
        final Bitmap[] bm = {null};
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL iconUrl = new URL(url);
                    URLConnection conn = iconUrl.openConnection();
                    HttpURLConnection http = (HttpURLConnection) conn;

                    int length = http.getContentLength();

                    conn.connect();
                    // 获得图像的字符流
                    InputStream is = conn.getInputStream();
                    BufferedInputStream bis = new BufferedInputStream(is, length);
                    bm[0] = BitmapFactory.decodeStream(bis);
                    bis.close();
                    is.close();// 关闭流
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();


        return bm[0];
    }

    private void IntenetData() {
        if (heigh == 0) {
            return;
        } else {
            new Thread(new Runnable() {

                @Override
                public void run() {
                    Intent intent = new Intent(context, DownQianDaoService.class);
                    intent.setPackage(getPackageName());
                    intent.setAction("updateData");
                    intent.putExtra("heigh", heigh);
                    intent.putExtra("firstLogin", "1");
                    startService(intent);
                }
            }).start();
        }
    }

    @Override
    protected void setAdapter() {
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tiaoguo_tv:
                LoaddingData(true, 1);
                break;
            case R.id.bj_image:
                if (!qiandaoFag) {
                    qiandaoFag = true;
                }
                LoaddingData(true, 0);
                break;
            default:
                break;
        }
    }

    private Runnable runnable = new Runnable() {

        @Override
        public void run() {
            LoaddingData(isStartActivity, type);
        }
    };

    private Intent LoaddingData(boolean isStartActivity, int type) {
        Intent intent = null;
        File file = new File("/data/data/com.mission.schedule/databases/plan");
        if (file.exists() && !file.isDirectory() && "0".equals(updateState)) {// &&"0".equals(updateState)
            makeFilePath(Environment.getExternalStorageDirectory().getPath() + "/YourAppDataFolder/", "plan");
            copyFile("/data/data/com.mission.schedule/databases/plan",
                    Environment.getExternalStorageDirectory().getPath() + "/YourAppDataFolder/" + "/plan");
            new WriteDataBase().execute();
            intent = new Intent(WelcomeActivity.this, DataUpdateActivity.class);
        } else if (file.exists() && !file.isDirectory()) {
            makeFilePath(Environment.getExternalStorageDirectory().getPath()
                    + "/YourAppDataFolder/", "plan");
            copyFile("/data/data/com.mission.schedule/databases/plan",
                    Environment.getExternalStorageDirectory().getPath()
                            + "/YourAppDataFolder/" + "/plan");
            if ("".equals(userId) || "0".equals(userId)) {
//                intent = register();
//                if (sharePrefUtil.getString(context, ShareFile.USERFILE, ShareFile.ISNEWLOCAL, "1").equals("1")) {
                r();
//                }

//                if (welcome_login_type.equals("0")){
//                    intent = new Intent(WelcomeActivity.this, PhoneCodeLoginNewActivity.class);
//                    intent.putExtra("type", 0);
//                    intent.putExtra("login", true);
//                } else {
//                    intent = new Intent(WelcomeActivity.this, NewLoginActivity.class);
//                }
            } else {
                if (sharePrefUtil.getString(context, ShareFile.USERFILE, ShareFile.ISLOGINNEWNEXT, "").equals("1")) {
                    intent = new Intent(WelcomeActivity.this, PhoneCodeLoginNewNextActivity.class);
                } else {
                    intent = new Intent(WelcomeActivity.this, MainActivity.class);
                }
            }
        } else {
            if ("".equals(userId) || "0".equals(userId)) {
//                intent = register();
//                if (sharePrefUtil.getString(context, ShareFile.USERFILE, ShareFile.ISNEWLOCAL, "1").equals("1")) {
                r();
//                }
//                if (welcome_login_type.equals("0")){
//                    intent = new Intent(WelcomeActivity.this, PhoneCodeLoginNewActivity.class);
//                    intent.putExtra("type", 0);
//                    intent.putExtra("login", true);
//                } else {
//                    intent = new Intent(WelcomeActivity.this, NewLoginActivity.class);
//                }
            } else {
                if (sharePrefUtil.getString(context, ShareFile.USERFILE, ShareFile.ISLOGINNEWNEXT, "").equals("1")) {
                    intent = new Intent(WelcomeActivity.this, PhoneCodeLoginNewNextActivity.class);
                } else {
                    intent = new Intent(WelcomeActivity.this, MainActivity.class);
                }
            }
        }
        if (intent == null) {
            return null;
        }
        if (isStartActivity) {
            startActivity(intent);
            // 设置切换动画，从右边进入，左边退出
            if (type == 1) {
                overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
            }
            finish();
        }
        return intent;
//        if (sharePrefUtil.getString(getApplication(), ShareFile.USERFILE, ShareFile.ISNEWYOUKE, "0").equals("-1")) {
//            if (qiandaoFag) {
//                new Thread(new Runnable() {
//                    @Override
//                    public void run() {
//                        String path = URLConstants.签到 + userId + "&tp.signDate=" + today
//                                + "&tp.signIntegral="
//                                + App.getDBcApplication().todayJifen()
//                                + "&tp.remark=android";
//                        StringRequest request = new StringRequest(Method.GET, path,
//                                new Listener<String>() {
//
//                                    @Override
//                                    public void onResponse(final String result) {
//                                        sharePrefUtil.putString(context, ShareFile.USERFILE, ShareFile.QIANDAODATE, DateUtil.formatDate(new Date()));
//                                        qiandaoFag = false;
//                                        downLocalQiandaoLog();
//                                    }
//                                }, new Response.ErrorListener() {
//
//                            @Override
//                            public void onErrorResponse(VolleyError error) {
//                                qiandaoFag = false;
//                                downLocalQiandaoLog();
//                            }
//                        });
//                        request.setTag("qiandao");
//                        request.setRetryPolicy(new DefaultRetryPolicy(10000, 1, 1.0f));
//                        App.getHttpQueues().add(request);
//                    }
//                }).start();
//            }
//        }
    }

    ProgressUtil progressUtil;
    int register = 0;

    private Intent register() {
        if (register > 5) {
            Toast.makeText(this, "网络异常", Toast.LENGTH_SHORT).show();
            return null;
        }
        Intent intent = new Intent(WelcomeActivity.this, MainActivity.class);
        progressUtil = new ProgressUtil();
        progressUtil.ShowProgress(this, true, true, "初始化数据...");
        OkHttpClient client = new OkHttpClient();
        Request.Builder request = new Request.Builder();
        HttpUrl.Builder builder = HttpUrl.parse("http://192.168.3.145:8080/timetable/user_regisTimetableByAddress.do").newBuilder();
        builder.addQueryParameter("uId", userId);
        builder.addQueryParameter("data", JPushInterface.getRegistrationID(getApplicationContext()));
        request.url(builder.build());
        Request request1 = request.build();
        try {
            okhttp3.Response response = client.newCall(request1).execute();
            if (response.code() == 200 && !response.body().string().isEmpty()) {
                String s = response.body().string();
                Gson gson = new Gson();
                PhoneCodeLoginNewActivity.LoginBean loginBean = gson.fromJson(s, PhoneCodeLoginNewActivity.LoginBean.class);
                if (loginBean.status == 0) {
                    WriteAlarmClock.clearAlarmClock(context);
                    List<PhoneCodeLoginNewActivity.LoginBean.ListBean> list = loginBean.list;
                    if (list.size() > 0) {
                        sharePrefUtil.putString(context, ShareFile.USERFILE, ShareFile.NewMyFoundFenXiangFirst, "1");
                        sharePrefUtil.putString(context, ShareFile.USERFILE, ShareFile.ISYOUKE, "1");
                        sharePrefUtil.putString(context, ShareFile.USERFILE, ShareFile.USEREMAIL, list.get(0).uEmail);
                        sharePrefUtil.putString(context, ShareFile.USERFILE, ShareFile.TELEPHONE, list.get(0).uMobile);
                        sharePrefUtil.putString(context, ShareFile.USERFILE, ShareFile.USERID, list.get(0).uId + "");
                        sharePrefUtil.putString(context, ShareFile.USERFILE, ShareFile.USERNAME, list.get(0).uNickName);
                        sharePrefUtil.putString(context, ShareFile.USERFILE, ShareFile.USERSTATE, "1");
                        sharePrefUtil.putString(context, ShareFile.USERFILE, ShareFile.USERBACKGROUNDPATH, list.get(0).uBackgroundImage);
                        sharePrefUtil.putString(context, ShareFile.USERFILE, ShareFile.PERSONREMARK, list.get(0).uPersontag);
                        if (!"".equals(list.get(0).uPortrait)) {
                            String str = list.get(0).uPortrait;
                            str = str.replace("\\", "");
                            sharePrefUtil.putString(context, ShareFile.USERFILE, ShareFile.USERPHOTOPATH, str);
                        }
                        sharePrefUtil.putString(getApplication(), ShareFile.USERFILE, ShareFile.FIRSTOPENAPP, "1");
                        sharePrefUtil.putString(context, ShareFile.USERFILE, ShareFile.U_ACC_NO, list.get(0).uAccNo);
                        sharePrefUtil.putString(context, ShareFile.USERFILE, ShareFile.ISYOUKE, list.get(0).uIsActive + "");
                        sharePrefUtil.putString(context, ShareFile.USERFILE, ShareFile.SHUNYANTYPE, "0");
                        sharePrefUtil.putString(context, ShareFile.USERFILE, ShareFile.ISNEWYOUKE, "-1");
                        App.getDBcApplication().douleClear();
                        new WriteDataBase().execute();
                        getJson();
                        Intent tagintent = new Intent(context, UpdataTagService.class);
                        tagintent.setAction("UpdataTagService");
                        tagintent.putExtra("down", "downtag");
                        tagintent.setPackage(getPackageName());
                        startService(tagintent);
                        sharePrefUtil.putString(context, ShareFile.USERFILE, ShareFile.FIRSTLOGIN, "1");
                        sharePrefUtil.putString(getApplicationContext(), ShareFile.USERFILE, ShareFile.LOGINTYPE, "0");
                        intent = new Intent(context, PhoneCodeLoginNewNextActivity.class);
                        WelcomeActivity.this.finish();
                    }
                }
            } else {
                register++;
                Toast.makeText(this, "网络异常,请检测网络", Toast.LENGTH_SHORT).show();
                register();
            }
            progressUtil.dismiss();
        } catch (IOException e) {
            progressUtil.dismiss();
            register++;
            Toast.makeText(this, "网络异常,请检测网络", Toast.LENGTH_SHORT).show();
            intent = register();
            register();
            e.printStackTrace();
        }
        return intent;
    }

    private void r() {
        progressUtil = new ProgressUtil();
        progressUtil.ShowProgress(this, true, true, "初始化数据...");
        new Thread(() -> {
            String path = "http://www.keytimeapp.com/user_regisTimetableByAddress.do?uId="
                    + (userId.equals("0") ? "" : userId) + "&data=TimeSheet_A_"
                    + GetDeviceId.getDeviceId(context).replaceAll(":", "0").replaceAll("%", "1");
            StringRequest request = new StringRequest(Method.GET, path,
                    result -> {
                        progressUtil.dismiss();
                        Gson gson = new Gson();
                        PhoneCodeLoginNewActivity.LoginBean loginBean = gson.fromJson(result, PhoneCodeLoginNewActivity.LoginBean.class);
                        if (loginBean.status == 0) {
                            WriteAlarmClock.clearAlarmClock(context);
                            List<PhoneCodeLoginNewActivity.LoginBean.ListBean> list = loginBean.list;
                            if (list.size() > 0) {
                                sharePrefUtil.putString(context, ShareFile.USERFILE, ShareFile.NewMyFoundFenXiangFirst, "1");
                                sharePrefUtil.putString(context, ShareFile.USERFILE, ShareFile.ISYOUKE, "1");
                                sharePrefUtil.putString(context, ShareFile.USERFILE, ShareFile.USEREMAIL, list.get(0).uEmail);
                                sharePrefUtil.putString(context, ShareFile.USERFILE, ShareFile.TELEPHONE, list.get(0).uMobile);
                                sharePrefUtil.putString(context, ShareFile.USERFILE, ShareFile.USERID, list.get(0).uId + "");
                                sharePrefUtil.putString(context, ShareFile.USERFILE, ShareFile.USERNAME, list.get(0).uNickName);
                                sharePrefUtil.putString(context, ShareFile.USERFILE, ShareFile.USERSTATE, "1");
                                sharePrefUtil.putString(context, ShareFile.USERFILE, ShareFile.USERBACKGROUNDPATH, list.get(0).uBackgroundImage);
                                sharePrefUtil.putString(context, ShareFile.USERFILE, ShareFile.PERSONREMARK, list.get(0).uPersontag);
                                if (!"".equals(list.get(0).uPortrait)) {
                                    String str = list.get(0).uPortrait;
                                    str = str.replace("\\", "");
                                    sharePrefUtil.putString(context, ShareFile.USERFILE, ShareFile.USERPHOTOPATH, str);
                                }
                                sharePrefUtil.putString(getApplication(), ShareFile.USERFILE, ShareFile.FIRSTOPENAPP, "1");
                                sharePrefUtil.putString(context, ShareFile.USERFILE, ShareFile.U_ACC_NO, list.get(0).uAccNo);
                                sharePrefUtil.putString(context, ShareFile.USERFILE, ShareFile.ISYOUKE, list.get(0).uIsActive + "");
                                sharePrefUtil.putString(context, ShareFile.USERFILE, ShareFile.SHUNYANTYPE, "0");
                                sharePrefUtil.putString(context, ShareFile.USERFILE, ShareFile.ISNEWYOUKE, "-1");
                                App.getDBcApplication().douleClear();
                                new WriteDataBase().execute();
                                getJson();
                                Intent tagintent = new Intent(context, UpdataTagService.class);
                                tagintent.setAction("UpdataTagService");
                                tagintent.putExtra("down", "downtag");
                                tagintent.setPackage(getPackageName());
                                startService(tagintent);
                                sharePrefUtil.putString(context, ShareFile.USERFILE, ShareFile.FIRSTLOGIN, "1");
                                sharePrefUtil.putString(context, ShareFile.USERFILE, ShareFile.ISNEWLOCAL, "0");
                                sharePrefUtil.putString(getApplicationContext(), ShareFile.USERFILE, ShareFile.LOGINTYPE, "0");
                                startActivity(new Intent(context, PhoneCodeLoginNewNextActivity.class));
                                finish();
                            }
                        }
                    }, error -> {
                progressUtil.dismiss();
                Toast.makeText(this, "网络异常,请检测网络", Toast.LENGTH_SHORT).show();
            });
            request.setTag("qiandao");
            request.setRetryPolicy(new DefaultRetryPolicy(10000, 1, 1.0f));
            App.getHttpQueues().add(request);
        }).start();
    }

    private void downLocalQiandaoLog() {
        HttpUtils httpUtils = new HttpUtils(10000);
        RequestParams params = new RequestParams();
        params.addBodyParameter("uid", userId);
        httpUtils.send(HttpMethod.POST, URLConstants.签到当月日志下行, params,
                new RequestCallBack<String>() {

                    @Override
                    public void onFailure(HttpException e, String msg) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        if (!TextUtils.isEmpty(responseInfo.result)) {
                            sharePrefUtil.putString(WelcomeActivity.this, ShareFile.USERFILE,
                                    ShareFile.QIANDAOSTRING, responseInfo.result);
                        }
                    }
                });


    }

    /**
     * @param oldPath String 原文件路径
     * @param newPath String 复制后路径
     * @return boolean
     */
    public void copyFile(String oldPath, String newPath) {
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) { // 文件存在时
                InputStream inStream = new FileInputStream(oldPath); // 读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1024];
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; // 字节数 文件大小
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
        } catch (Exception e) {
            System.out.println("复制单个文件操作出错");
            e.printStackTrace();

        }

    }

    // 生成文件
    public File makeFilePath(String filePath, String fileName) {
        File file = null;
        makeRootDirectory(context, filePath);
        try {
            file = getExternalFilesDir(filePath + fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

    // 生成文件夹
    public static void makeRootDirectory(Context context, String filePath) {
        File file = null;
        try {
            file = context.getExternalFilesDir(filePath);
            if (!file.exists()) {
                file.mkdir();
            }
        } catch (Exception e) {
        }
    }

    class WriteDataBase extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {
            toWriteData(DBSourse.dataBaseName, R.raw.data);
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
        }

    }

    /**
     * 初始化数据库
     *
     * @param dataBaseName
     * @param resourse
     */
    private void toWriteData(String dataBaseName, int resourse) {
        InputStream is = getResources().openRawResource(resourse); // 欲导入的数据库
        OutputStream fos;
        try {
            String dbpath = "/data/data/com.mission.schedule/databases/" + dataBaseName;
            if (DBSourse.createFile(dbpath)) {
                fos = new FileOutputStream(dbpath);
                byte[] buffer = new byte[1024];
                int count = 0;
                while ((count = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, count);
                }
                fos.flush();
                fos.close();
                is.close();
                SharedPreferences sp = getSharedPreferences("localchedule",
                        Context.MODE_PRIVATE);
                SharedPreferences.Editor e = sp.edit();
                e.putString("isDataWrite", "1");// 0为写入数据库文件
                e.commit();
                Log.d("TAG", "数据库导入成功");
            } else {
                handler.sendEmptyMessage(0);
                Log.d("TAG", "数据库导入失败");
            }
        } catch (Exception e) {
            handler.sendEmptyMessage(0);
            Log.d("TAG", "数据库导入失败");
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (TextUtils.isEmpty(isUserFirstInstall)) {
            UserProtocolTipDialog userProtocolTipDialog = new UserProtocolTipDialog(this, R.style.dialog_translucent);
            userProtocolTipDialog.setCallBack(new UserProtocolTipDialog.CallBack() {
                @Override
                public void agree() {
                    isStartActivity = true;
                    LoadData();
                }

                @Override
                public void reject() {
                    finish();
                }
            });
            userProtocolTipDialog.show();
        } else {
            isStartActivity = false;
            LoadData();
            loadBaiDuAd();
        }
    }

    private void loadBaiDuAd() {
        background_rl.setVisibility(View.VISIBLE);
        // 重要：请填上您的广告位ID，代码位错误会导致无法请求到广告
        final String adPlaceId = "7922501";
        //        AdSettings.setSupportHttps(false); // 自由选择使用http或者https请求，默认https
        //        SplashAd.setBitmapDisplayMode(BitmapDisplayMode.DISPLAY_MODE_FIT_XY);// 根据需求自由设置开屏图片拉伸方式
        // 设置视频广告最大缓存占用空间(15MB~100MB),默认30MB,单位MB
        // SplashAd.setMaxVideoCacheCapacityMb(30);
        // 1. 设置开屏listener
        final SplashInteractionListener listener = new SplashInteractionListener() {
            @Override
            public void onLpClosed() {
                Log.i("11111", "lp页面关闭");
                // 落地页关闭后关闭广告，并跳转到应用的主页
                jump();
            }

            @Override
            public void onAdDismissed() {
                Log.i("11111", "onAdDismissed");
                jumpWhenCanClick(); // 跳转至您的应用主界面
            }

            @Override
            public void onADLoaded() {
                Log.i("11111", "onADLoaded");
                Log.i("11111", "ECPM level:" + splashAd.getECPMLevel());
            }

            @Override
            public void onAdFailed(String reason) {
                Log.i("11111", "onAdFailed:" + reason);
                jump();
            }

            @Override
            public void onAdPresent() {
                adsParent.setVisibility(View.VISIBLE);
                Log.i("11111", "onAdPresent");
            }

            @Override
            public void onAdClick() {
                Log.i("11111", "onAdClick");
                isClickAd = true;
            }

            @Override
            public void onAdCacheSuccess() {
                Log.i("11111", "onAdCacheSuccess");
            }

            @Override
            public void onAdCacheFailed() {
                Log.i("11111", "onAdCacheFailed");
            }
        };
        adsParent.setVisibility(View.VISIBLE);
        // 如果开屏需要load广告和show广告分开，请参考类RSplashManagerActivity的写法
        // 如果需要修改开屏超时时间、隐藏工信部下载整改展示，请设置下面代码;
        final RequestParameters.Builder parameters = new RequestParameters.Builder();
        // sdk内部默认超时时间为4200，单位：毫秒
        parameters.addExtra(SplashAd.KEY_TIMEOUT, "4200");
        // sdk内部默认值为true
        parameters.addExtra(SplashAd.KEY_DISPLAY_DOWNLOADINFO, "true");
        // 是否限制点击区域，默认不限制
        parameters.addExtra(SplashAd.KEY_LIMIT_REGION_CLICK, "false");
        // 是否展示点击引导按钮，默认不展示，若设置可限制点击区域，则此选项默认打开
        parameters.addExtra(SplashAd.KEY_DISPLAY_CLICK_REGION, "true");
        // 用户点击开屏下载类广告时，是否弹出Dialog
        // 此选项设置为true的情况下，会覆盖掉 {SplashAd.KEY_DISPLAY_DOWNLOADINFO} 的设置
        parameters.addExtra(SplashAd.KEY_POPDIALOG_DOWNLOAD, "true");
        splashAd = new SplashAd(this, adPlaceId, parameters.build(), listener);
        splashAd.loadAndShow(adsParent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        JPushInterface.onResume(context);
        if (canJumpImmediately) {
            jumpWhenCanClick();
        }
        canJumpImmediately = true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        JPushInterface.onPause(context);
        canJumpImmediately = false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // Activity销毁时，销毁广告对象释放资源，避免潜在的内存泄露
        if (splashAd != null) {
            splashAd.destroy();
            splashAd = null;
        }
        App.getHttpQueues().cancelAll("qiandao");
        this.finish();
    }

    /**
     * 取SD卡路径
     **/
    private String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory(); // 获取根目录
        }
        if (sdDir != null) {
            return sdDir.toString();
        } else {
            return "";
        }
    }

    /**
     * 获得缓存目录
     **/
    private String getDirectory() {
        String dir = getSDPath() + "/" + CACHDIR;
        return dir;
    }

    private void getJson() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                StringBuilder sb = new StringBuilder();
                try {
                    AssetManager assetManager = context.getAssets();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(assetManager.open("cytx.json")));
                    String line;
                    while ((line = bufferedReader.readLine()) != null) {
                        sb.append(line);
                    }
                    sharePrefUtil.putString(context, ShareFile.USERFILE,
                            ShareFile.CYTXJSON, sb.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
